package com.cherry.common.util;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * Bean 工具类
 *
 * @author sinbad.cheng
 * @since 2022-07-22
 */
public final class BeanUtil {

    private BeanUtil() {
    }

    /**
     * 对象转Map
     *
     * @param object 对象
     * @return {@link Map}
     */
    public static Map<String, Object> toMap(Object object) {
        if (object == null) {
            return Collections.emptyMap();
        }

        // map 类型直接返回
        if (object instanceof Map) {
            return (Map<String, Object>) object;
        }

        Class<?> aClass = object.getClass();
        // 不支持原始类型
        boolean isPrimitive = aClass.isPrimitive();
        if (isPrimitive) {
            throw new IllegalArgumentException("data type is primitive");
        }

        // 属性自省获取
        PropertyDescriptor[] propertyDescriptors = null;
        try {
            propertyDescriptors = Introspector.getBeanInfo(aClass, Object.class).getPropertyDescriptors();
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
        // 属性为空，直接返回
        if (propertyDescriptors == null || propertyDescriptors.length == 0) {
            return Collections.emptyMap();
        }

        // 迭代字段转 Map
        HashMap<String, Object> hashMap = new HashMap<>(Math.max((int) (propertyDescriptors.length / .75f) + 1, 16));
        try {
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String fieldName = propertyDescriptor.getName();
                Method readMethod = propertyDescriptor.getReadMethod();
                if (readMethod == null) {
                    continue;
                }
                Object value = readMethod.invoke(object);
                hashMap.put(fieldName, value);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return hashMap;
    }

    /**
     * Map 转 Bean
     *
     * @param map    Map数据
     * @param aClass 类
     * @return Bean 对象
     */
    public static <T> T mapToBean(Map<String, ?> map, Class<T> aClass) {
        T t = null;
        try {
            t = aClass.newInstance();
        } catch (IllegalAccessException | InstantiationException e) {
            throw new RuntimeException(e);
        }

        // map 为空，直接返回对象
        if (map == null || map.isEmpty()) {
            return t;
        }

        // 属性自省获取
        PropertyDescriptor[] propertyDescriptors = null;
        try {
            propertyDescriptors = Introspector.getBeanInfo(aClass, Object.class).getPropertyDescriptors();
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        }
        // 属性为空，直接返回
        if (propertyDescriptors == null || propertyDescriptors.length == 0) {
            return t;
        }

        // 根据字段获取 Map 数据，并调用 writeMethod 赋值
        try {
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String fieldName = propertyDescriptor.getName();
                Object value = map.get(fieldName);
                if (value == null) {
                    continue;
                }
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (writeMethod == null) {
                    continue;
                }
                writeMethod.invoke(t, value);
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return t;
    }

    /**
     * beans 转 maps
     *
     * @param beans 转换对象
     * @return 转换后的 Map 集合
     */
    public static <T> List<Map<String, Object>> beansToMaps(List<T> beans) {
        if (beans == null || beans.isEmpty()) {
            return Collections.emptyList();
        }
        return beans.stream().map(BeanUtil::toMap).collect(toList());
    }

    /**
     * maps 转 beans
     *
     * @param maps  转换 MAP 集合
     * @param clazz 对象 Class
     * @return 返回转换后的 bean 集合
     */
    public static <T> List<T> mapsToBeans(List<? extends Map<String, ?>> maps, Class<T> clazz) {
        if (maps == null || maps.isEmpty()) {
            return Collections.emptyList();
        }
        return maps.stream().map(e -> mapToBean(e, clazz)).collect(toList());
    }

}